/* 
上传图片：点击选择图片，直接图片裁剪，裁剪后点击确定上传
父组件中引用

import imageUpload from "@/pages/manage/release/imageUpload";
components: {
  imageUpload,
},

<image-upload
  :limit="5"
  :previewImg="cmdyChart"
  @imageChange="imageChange"
></image-upload>

imageChange(e) {
  this.imglist = e
},
*/
<template>
  <view class="pho-option flexWrap">
    <view
      v-if="imgList && imgList.length > 0"
      class="pho-show"
      @click="prevImag(index)"
      v-for="(item, index) in imgList"
      :key="index"
    >
      <image :src="item" mode=""></image>
      <icon
        type="clear"
        size="16"
        class="delete"
        @click.stop="deletePhoto(index)"
      ></icon>
    </view>
    <view class="pho-add" v-if="imgList.length < limit" @click="uploadType()">
      <image src="@/static/images/manage/addphoto.png" mode=""></image>
      <view class="">点击上传</view>
    </view>
    <choose-modal ref="modal" @getVal="getVal"></choose-modal>
    <!-- 裁剪 -->
    <ksp-image-cutter
      v-if="url"
      @ok="onok"
      @cancel="url = ''"
      :url="url"
      :fixed="true"
      :width="750"
      :height="750"
    ></ksp-image-cutter>
  </view>
</template>

<script>
import chooseModal from "@/components/choose-modal";    //  选择图片做兼容处理
import config from "@/config/index.js";   //  域名前缀
import kspImageCutter from "@/components/ksp-image-cutter/ksp-image-cutter";    // 裁剪组件
export default {
  components: {
    chooseModal,
    kspImageCutter,
  },
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    previewImg: {
      type: String,
      default: "",
    },
    ltSize: {
      type: Number,
      default: 2,
    },
  },
  data() {
    return {
      imgList: [],
      recordType: ["album"],
      platform: uni.getSystemInfoSync().platform,
      url: "",
    };
  },
  watch: {
    previewImg: {
      handler(newVal, oldVal) {
        console.log(newVal, "watch监听");
        this.imgList = newVal ? newVal.split(",") : [];
      },
    },
  },
  methods: {
    getVal(val) {
      if (val !== "0") {
        this.recordType = val === "2" ? ["album"] : ["camera"];
        this.chooseImage();
      }
    },
    uploadType() {
      if (this.platform === "android") {
        this.$refs.modal.open();
      } else {
        this.recordType = ["camera", "album"];
        this.chooseImage();
      }
    },
    chooseImage() {
      uni.chooseImage({
        count: 1, // 最多可以选择的图片张数，默认9
        sourceType: this.recordType,
        success: (res) => {
          let filePath = res.tempFilePaths[0];
          let fileObj = res.tempFiles[0];
          if (!/\.(png|jpg|jpeg)$/i.test(filePath)) {
            this.msg("请上传PNG、JPG、JPEG格式的图片", { duration: 2000 });
            return;
          }
          if (fileObj.size > this.ltSize * 1024 * 1024) {
            this.msg(`图片不能大于${this.ltSize}M`, { duration: 2000 });
            return;
          }
          this.url = res.tempFilePaths[0];
        },
      });
    },
    // 裁剪图片
    onok(res) {
      this.url = "";
      this.upload(res);
    },
    // 上传
    upload(filePath) {
      // 上传图片
      uni.showLoading({
        title: "上传中",
      });
      const baseUrlWeiXin = config.apibaseUrlWeiXin;
      uni.uploadFile({
        url: `${baseUrlWeiXin}${this.$API.manage.upload.uploadImage}`,
        filePath: filePath,
        name: "file",
        header: {
          "X-Access-Token": uni.getStorageSync("Token"),
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.success) {
            this.imgList.push(data.result);
            this.$emit("imageChange", this.imgList.join(","));
          }
        },
        fail: () => {
          console.log("上传商品主图失败");
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },
    deletePhoto(index) {
      this.imgList.splice(index, 1);
      this.$emit("imageChange", this.imgList ? this.imgList.join(",") : "");
    },
    prevImag(current) {
      uni.previewImage({
        current: current,
        urls: this.imgList,
      });
    },
  },
  upload() {},
};
</script>

<style lang='scss' scoped>
.pho-option {
  + .pho-option {
    margin-left: 20rpx;
  }
}

.pho-add {
  width: 210rpx;
  height: 210rpx;
  background-color: $uni-bg-color-add;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 10rpx;

  image {
    width: 81rpx;
    height: 74rpx;
    margin-bottom: 24rpx;
  }

  text {
    font-size: 28rpx;
    font-weight: 400;
    color: $uni-text-color;
  }
}

.pho-show {
  width: 210rpx;
  height: 210rpx;
  margin: 0 30rpx 30rpx 0;
  position: relative;
  border-radius: 10rpx;

  image {
    object-fit: contain;
    border-radius: 10rpx;
    background: #e5e5e5;
  }

  .delete {
    position: absolute;
    top: 3rpx;
    right: 3rpx;
  }
}

.pho-show:nth-child(3n) {
  margin-right: 0;
}

.flexWrap {
  display: flex;
  flex-wrap: wrap;
}
</style>
